import { ChangeEventHandler, useEffect, useState } from "react"
import { Button, message } from "antd"
import JSZip from 'jszip'
import { getStorageManager } from '@/storage'
import { dataURItoBlob, sanitizeFileName, uniqueName } from '@/storage/utils'
import log from "@/storage/log"
import LazyImage from "./LazyImage"

export default function VisualList() {

    const [list, setList] = useState<any[]>([])

    // 获取列表
    const getList = () => {
        getStorageManager().getVisionStorage().list().then(list => {
            console.log(list)
            setList(list)
        })
    }

    // 上传Visual
    const onImageFileChange: ChangeEventHandler<HTMLInputElement> = (e) => {
        const files = [].slice.call(e.target.files)
        if (!files || !files.length) return

        const read = (file: File) => {
            return new Promise((resolve, reject) => {
                const reader = new FileReader()

                reader.onload = (readerEvent) => {
                    try {
                        const dataUrl = readerEvent.target!.result
                        const obj = storeImage({ dataUrl, name: file.name })
                        resolve(obj)
                    } catch (e) {
                        resolve({ err: e, fileName: file.name })
                    }
                }

                reader.readAsDataURL(file)
            })
        }

        const storeImage = ({ dataUrl, name }: { dataUrl: any, name: string }) => {
            return uniqueName(name, {
                check: (name: string) => {
                    return getStorageManager()
                        .getVisionStorage()
                        .exists(name)
                        .then(result => !result)
                }
            })
                .then((fileName: string) => {
                    return getStorageManager()
                        .getVisionStorage()
                        .write(sanitizeFileName(fileName), dataURItoBlob(dataUrl))
                        .then(() => fileName)
                })
                .catch((e: Error) => {
                    log.error(e.stack)
                })
        }

        Promise.all(files.map(read))
            .then(fileNames => {
                message.success(`${fileNames.length} image files imported into Vision tab`)
                getList()
            })
            .catch(e => {
                log.error(e.stack)
            })
    }

    // 导出全部
    const exportAllVisions = () => {
        const zip = new JSZip()
        const visionStorage = getStorageManager().getVisionStorage()

        visionStorage.list().then((visions: any) => {

            if (visions.length === 0) {
                message.error('No vision to export')
                return
            }

            const ps = visions.map((ss: any) => {
                return visionStorage.read(ss.fullPath, 'ArrayBuffer')
                    .then((buffer: any) => {
                        zip.file(ss.name, buffer, { binary: true })
                    })
            })

            return Promise.all(ps)
                .then(() => {
                    zip.generateAsync({ type: 'blob' })
                        .then(function (blob: any) {
                            // 3. 创建下载链接并触发下载
                            const url = URL.createObjectURL(blob);
                            const link = document.createElement('a');
                            link.href = url;
                            link.download = "vision-images-export.zip"; // 下载文件名
                            document.body.appendChild(link);
                            link.click();

                            // 4. 清理临时URL
                            setTimeout(() => {
                                URL.revokeObjectURL(url);
                                document.body.removeChild(link);
                            }, 0);
                        })
                })
        })
    }

    // 请求数据
    useEffect(() => {
        getList()
    }, [])

    return <div>
        <span
            className="load-image-button ant-btn ant-btn-primary"
        >
            <label htmlFor="select_image_files">上传图片</label>
            <input
                multiple
                type="file"
                accept="image/*"
                id="select_image_files"
                onChange={onImageFileChange}
                style={{ display: 'none' }}
            />
        </span>
        <span onClick={exportAllVisions}>导出全部</span>
        <ul className="screntshot-list">
            {
                list.map(item => {
                    return <li key={item.fullPath}>
                        <LazyImage fullPath={item.fullPath} />
                        <span>{item.name}</span>
                    </li>
                })
            }
        </ul>
    </div>
}